<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>解析历史</span>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="视频标题" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入视频标题"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="平台" prop="platform">
          <el-select v-model="queryParams.platform" placeholder="选择平台" clearable>
            <el-option
              v-for="item in platformOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="解析时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮区域 -->
      <el-row :gutter="10" class="mb-10">
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            :disabled="multiple"
            @click="handleDelete"
          >批量删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            @click="handleExport"
          >导出</el-button>
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="historyList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="ID" prop="id" width="80" />
        <el-table-column label="视频标题" prop="title" :show-overflow-tooltip="true" />
        <el-table-column label="平台" prop="platform" width="100" />
        <el-table-column label="时长" prop="duration" width="100" />
        <el-table-column label="封面" width="100">
          <template #default="scope">
            <el-image 
              v-if="scope.row.cover"
              :src="scope.row.cover" 
              style="width: 60px; height: 40px"
              :preview-src-list="[scope.row.cover]"
            />
            <span v-else>无封面</span>
          </template>
        </el-table-column>
        <el-table-column label="解析时间" prop="createTime" width="160" />
        <el-table-column label="解析用户" prop="username" width="120" />
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleView(scope.row)"
            >查看</el-button>
            <el-button
              type="success"
              link
              @click="handleReparse(scope.row)"
            >重新解析</el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page="queryParams.pageNum"
        :limit="queryParams.pageSize"
        @pagination="handlePagination"
      />

      <!-- 查看详情对话框 -->
      <el-dialog :title="'视频详情 - ' + (viewData.title || '')" v-model="openView" width="800px" append-to-body>
        <div class="view-container" v-if="viewData">
          <div class="video-info">
            <div class="video-meta">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="视频标题">{{ viewData.title }}</el-descriptions-item>
                <el-descriptions-item label="视频平台">{{ viewData.platform }}</el-descriptions-item>
                <el-descriptions-item label="作者">{{ viewData.author }}</el-descriptions-item>
                <el-descriptions-item label="时长">{{ viewData.duration }}</el-descriptions-item>
                <el-descriptions-item label="解析时间">{{ viewData.createTime }}</el-descriptions-item>
                <el-descriptions-item label="解析用户">{{ viewData.username }}</el-descriptions-item>
                <el-descriptions-item label="原始链接" :span="2">
                  <el-link type="primary" :href="viewData.originalUrl" target="_blank" :underline="false">
                    {{ viewData.originalUrl }}
                  </el-link>
                  <el-button type="primary" link @click="copyText(viewData.originalUrl)">复制</el-button>
                </el-descriptions-item>
              </el-descriptions>
            </div>
            
            <div class="video-cover" v-if="viewData.cover">
              <h4>视频封面</h4>
              <el-image 
                :src="viewData.cover" 
                style="max-width: 100%; max-height: 300px"
                :preview-src-list="[viewData.cover]"
              />
            </div>
            
            <div class="video-player" v-if="viewData.playUrl">
              <h4>视频播放</h4>
              <video 
                controls 
                :src="viewData.playUrl" 
                style="width: 100%; max-height: 400px;"
              ></video>
            </div>
            
            <div class="download-options" v-if="viewData.downloadUrls && viewData.downloadUrls.length > 0">
              <h4>下载选项</h4>
              <el-table :data="viewData.downloadUrls" style="width: 100%">
                <el-table-column prop="quality" label="清晰度" width="180"></el-table-column>
                <el-table-column prop="size" label="大小" width="180"></el-table-column>
                <el-table-column label="操作">
                  <template #default="scope">
                    <el-button 
                      type="primary" 
                      size="small" 
                      @click="handleDownload(scope.row.url, viewData.title)"
                    >
                      下载
                    </el-button>
                    <el-button 
                      type="info" 
                      size="small" 
                      @click="copyText(scope.row.url)"
                    >
                      复制链接
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getParseHistory, deleteParseHistory, parseVideo } from '@/api/video/parse'
import { getSupportedPlatforms } from '@/api/video/parse'
import Pagination from '@/components/Pagination'
import { useRouter } from 'vue-router'

const router = useRouter()

// 遮罩层
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非多个禁用
const multiple = ref(true)
// 总条数
const total = ref(0)
// 历史记录表格数据
const historyList = ref([])
// 查看对话框
const openView = ref(false)
// 查看的数据
const viewData = ref({})
// 日期范围
const dateRange = ref([])

// 平台选项
const platformOptions = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: undefined,
  platform: undefined,
  beginTime: undefined,
  endTime: undefined
})

// 获取平台选项
const getPlatformOptions = async () => {
  try {
    const res = await getSupportedPlatforms()
    if (res.code === 200) {
      platformOptions.value = res.data.map(item => ({
        value: item.code,
        label: item.name
      }))
    }
  } catch (error) {
    console.error('获取平台选项失败', error)
  }
}

// 获取历史记录列表
const getList = () => {
  loading.value = true
  // 处理日期范围
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.beginTime = dateRange.value[0]
    queryParams.endTime = dateRange.value[1]
  } else {
    queryParams.beginTime = undefined
    queryParams.endTime = undefined
  }
  
  getParseHistory(queryParams).then(response => {
    historyList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  dateRange.value = []
  queryParams.title = undefined
  queryParams.platform = undefined
  queryParams.beginTime = undefined
  queryParams.endTime = undefined
  queryParams.pageNum = 1
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  multiple.value = !selection.length
}

// 查看详情按钮操作
const handleView = (row) => {
  viewData.value = row
  openView.value = true
}

// 重新解析按钮操作
const handleReparse = (row) => {
  router.push({
    path: '/video/parse',
    query: { url: row.originalUrl }
  })
}

// 删除按钮操作
const handleDelete = (row) => {
  const historyIds = row?.id || ids.value
  if (!historyIds || (Array.isArray(historyIds) && historyIds.length === 0)) {
    ElMessage.warning('请选择要删除的记录')
    return
  }
  
  ElMessageBox.confirm('是否确认删除选中的历史记录?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return deleteParseHistory(historyIds)
  }).then(() => {
    getList()
    ElMessage.success('删除成功')
  })
}

// 导出按钮操作
const handleExport = () => {
  // 这里可以实现导出功能，可以调用后端导出接口
  ElMessage.success('导出功能待实现')
}

// 处理分页
const handlePagination = ({ page, limit }) => {
  queryParams.pageNum = page
  queryParams.pageSize = limit
  getList()
}

// 处理下载
const handleDownload = (url, title) => {
  // 创建一个隐藏的a标签用于下载
  const a = document.createElement('a')
  a.style.display = 'none'
  a.href = url
  a.download = title || '视频下载'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

// 复制文本
const copyText = (text) => {
  navigator.clipboard.writeText(text).then(() => {
    ElMessage.success('复制成功')
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制')
  })
}

onMounted(() => {
  getPlatformOptions()
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.box-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mb-10 {
  margin-bottom: 10px;
}

.view-container {
  .video-meta {
    margin-bottom: 20px;
  }
  
  .video-cover {
    margin-bottom: 20px;
    
    h4 {
      margin-top: 0;
      margin-bottom: 10px;
    }
  }
  
  .video-player {
    margin-bottom: 20px;
    
    h4 {
      margin-top: 0;
      margin-bottom: 10px;
    }
  }
  
  .download-options {
    h4 {
      margin-top: 0;
      margin-bottom: 10px;
    }
  }
}
</style>